(ns acst.models.memos
  (:use acst.config.error-config
        acst.config.success-config)
  (:require [clojure.java.jdbc :as sql]
            [acst.models.comments :refer :all]
            [acst.models.roles :refer [if-is-admin]]
            [acst.utils.sql-util :as sqlutil]
            [acst.utils.escape :refer [html-sanitizer]]
            [acst.models.db :as db]))

(defn insert-memo! [publisher_id  content]
  (let [safe-content (html-sanitizer content)]
    (db/insert! :memos
                {:publisher_id publisher_id
                 :content (if (> (count safe-content) 0) safe-content nil)
                 :status 0}))
  )

(defn find-memo-by-memoid [memoid]
  (db/query
    (:memo-not-found memos-error)
    ["SELECT username, memo_id, create_date, publisher_id, content, pic_url
     FROM memos, users WHERE user_id = publisher_id AND memo_id = ?" memoid]))

(defn find-all-memos [limit page]
  (db/query
    (:memo-not-found memos-error)
    ["SELECT memo_id, create_date, publisher_id, username, content, pic_url
     FROM memos, users WHERE user_id = publisher_id
     ORDER BY create_date LIMIT ? OFFSET ?" limit (* (- page 1) limit)]))

(defn delete-memo! [memo_id user_id]
  (sqlutil/handle-delete!
    user_id
    :memos                            ;;handle-delete!函数处理管理员可删除条目
    ["memo_id = ? AND publisher_id = ?" memo_id user_id]
    ["memo_id = ?" memo_id]
    (:delete-memo-success memos-result)
    (:delete-memo-failed memos-error)))

(defn insert-memo-comment! [memo_id publisher_id content reply_id]
  (insert-comment! :memo_comments memo_id publisher_id content reply_id)) ;;comments已做防xss处理

(defn find-memo-comments [memo_id limit page]
  (get-all-comment :memo_comments memo_id limit page))

(defn find-memo-comments-reply-tree [memo_id comment_id]
  (get-comment-reply-tree :memo_comments memo_id comment_id))

(defn delete-memo-comment! [memo_id comment_id user_id]
  (delete-comment! :memo_comments memo_id comment_id user_id))



